package net.cjw.initsb.controller.advice;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authz.AuthorizationException;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import net.cjw.initsb.common.ServiceResult;
import net.cjw.initsb.exception.test.MyException;

@ControllerAdvice
public class MyControllerAdvice {

	/**
	 * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
	 * 
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
	}

	/**
	 * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
	 * 
	 * @param model
	 */
	@ModelAttribute
	public void addAttributes(Model model) {
		model.addAttribute("author", "Magical Sam");
	}

	/**
	 * shiro没权限报错拦截返回json
	 */
	@ResponseBody
	@ExceptionHandler(value = AuthorizationException.class)
	public ServiceResult<String> errorHandler(Exception ex) {
		return ServiceResult.buildError("没有权限");
	}

	/**
	 * 拦截捕捉自定义异常 MyException.class
	 * 
	 * @param ex
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = MyException.class)
	public Map myErrorHandler(MyException ex) {
		Map map = new HashMap();
		map.put("code", ex.getCode());
		map.put("msg", ex.getMsg());
		return map;
	}

	// 需要整合jsp或freemarker之类的模块才能返回动态错误页,替换原来静态错误页只需要在static的error或public的error里面放[错误码.html]静态页面即可替换
	// @ExceptionHandler(value = MyException2.class)
	// public ModelAndView myErrorHandler2(MyException2 ex) {
	// ModelAndView modelAndView = new ModelAndView();
	// modelAndView.setViewName("error");
	// modelAndView.addObject("code", ex.getCode());
	// modelAndView.addObject("msg", ex.getMsg());
	// return modelAndView;
	// }
}